#!/bin/sh

# udhcpc script edited by Tim Riker <Tim@Rikers.org>

[ -z "$1" ] && echo "Error: should be called from udhcpc" && exit 1

RESOLV_CONF="/etc/resolv.conf"
[ -n "$broadcast" ] && BROADCAST="broadcast $broadcast"
[ -n "$subnet" ] && NETMASK="netmask $subnet"

case "$1" in
	deconfig)
		/sbin/ifconfig $interface 0.0.0.0
		;;

	renew|bound)
		/sbin/ifconfig $interface $ip $BROADCAST $NETMASK
		echo "$(date) ifconfig $interface $ip $BROADCAST $NETMASK" >> /var/log/udhcp.log

		if [ -n "$router" ] ; then
			echo "$(date) deleting routers" >> /var/log/udhcp.log
			echo "deleting routers"
			while route del default gw 0.0.0.0 dev $interface ; do
				:
			done

			metric=0
			for i in $router ; do
				echo "$(date) route add default gw $i dev $interface metric $((metric++))" >> /var/log/udhcp.log
				route add default gw $i dev $interface metric $((metric++))
			done

			# avoid resetting the resolv.conf for any additional netdevs,
			#  as the first is the one the Docker daemon will use to pull images
			if [ -n "$dns" ] ; then
				echo "$(date) reset $RESOLV_CONF" >> /var/log/udhcp.log
				echo -n > $RESOLV_CONF
			fi
			if [ -n "$domain" ] ; then
				echo "$(date) search $domain" >> /var/log/udhcp.log
				echo search $domain >> $RESOLV_CONF
			fi
		fi

		for i in $dns ; do
			echo "$(date) adding dns $i" >> /var/log/udhcp.log
			echo adding dns $i
			echo nameserver $i >> $RESOLV_CONF
		done
		;;
esac

exit 0
